<style lang="less" scoped>
.l {
  display: inline-block;
  width:200px;
  margin:0 20px 20px 0 !important;
}
.b {
  width:640px;
  display: block;
}
#header-button {
  position: relative;
  input {
   position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
    opacity: 0;
    z-index: 100;
  }
  .input-size {
    width:300px;
  }
}
.add-version-btn {
  margin-bottom: 20px;
  span {
    color:rgb(36, 197, 76);
    font-size: 14px;
    cursor: pointer;
  }
}
.del-version-btn {
  color:red;
  font-size: 14px;
  cursor: pointer;
}
video{
    width: 100%;
    height: 100%;
}
.clear-video-btn {
    margin: 30px;
}
</style>

<template lang="pug">
#add-article.admin
  el-form(ref='form', :model='form', label-width='80px', style="width:60%")
    el-input(class="l" placeholder='请输入文字名称', v-model='form.charName',@blur="checkIsRpeat",:disabled="!!isUpdate")
    el-input(class="l" placeholder='文字拼音', v-model='form.phoneticize')
    div(v-for="(versionItem,index) in versionList")
      el-select(class="l" placeholder="所属版本" v-model="versionItem.version")
        el-option(v-for="item in versions" :label="item.name" :value="item._id" :key="item._id")
      el-select(class="l" placeholder="所属年级" v-model="versionItem.grade" @change="gradeChange(versionItem.grade,index)")
        el-option(v-for="item in grades" :label="item.name" :value="item._id" :key="item._id")
      el-select(class="l" placeholder="所属课程" v-model.Number="versionItem.class")
        el-option(v-for="(item,index) in classes" :label="index+1" :value="index+1" :key="index+1")
      span(v-if="index !==0",class="del-version-btn",@click="delVersionHandle(index)") 删除
    div(class="add-version-btn")
      span(@click="addversionHandle") +新增版本
    el-select(class="b" placeholder="请选择标签" v-model="form.tag" multiple)
      el-option(v-for="item in tags" :label="item.name" :value="item._id" :key="item._id")
    el-button(class="clear-video-btn",type="primary",@click="clearVideoHandle") 清空视频
    #editor-header1.border1
      video(:src='form.video', alt='', v-if='form.video',controls="controls")
      #header-button(v-else)
        span 上传文字视频
        input(type="file" id="videoNode" value='点击上传 (必填)' @change="videoChange")
    //- #editor-header.border1
      //- img(:src='form.headerImg', alt='', v-if='form.headerImg')
      //- #header-button(v-else)
        //- span 点击上传文字封面 .jpg/.png (可选)
        //- input(type="file" value='点击上传 .jpg/.png (可选)' @change="picChange")
    .clearfix
      div
    //- el-button(class="capture-image",type="primary") 生成截图
    //- vmarkdown(v-if='isMarkdownEditor' v-bind:markdown='form.markdown')
    //- veditor#veditor(style="height:300px;max-height:500px;", v-else)
    commit-component(:_form         = 'form',
                     :dialogVisible = 'dialogVisible',
                     :onSubmit      = 'onSubmit',
                     :dialogConfim  = 'dialogConfim',
                     :dialogCancel  = 'dialogCancel')
</template>

<script>
import tools from "../../tools";
import * as api from "../../stores/api";

export default {
  name: "add-article",
  computed: {
    isMarkdownEditor() {
      return this.$store.state.isMarkdownEditor;
    },
    isUpdate() {
      return this.$route.query.id || undefined;
    }
  },
  data() {
    return {
      form: {
        charName: "", // 文字
        phoneticize:'', // 拼音
        tag:[], // 标签
        belongVersionList:[], // 所属的版本和年级
        video:'',
        headerImg: "",
        // sendAt: "",
        html: "",
        markdown: ""
      },
      versionList:[
        {
          version:'',
          grade:'',
          class:'',
        }
      ], // 版本和年级容器
      uptoken: "",
      editor: {},
      dialogVisible: false,
      formLabelWidth: "200px",
      grades:[], // 年级
      tags:[], // 文字的标签
      versions:[], // 版本
      classes:[], // 课程
      hasUpdate:false,
    };
  },
  methods: {
    // 检查文字是否重复输入
    checkIsRpeat() {
      if(!this.form.charName) return;
      api._get({
        url: 'search',
        data: {
          model: 'Article',
          searchKey: 'charName',
          searchVal: this.form.charName,
          start: 0,
        }
      }).then((result) => {
        if (result.status === 200) {
            if(result.data.data && result.data.data.list && result.data.data.list.length > 0) {
              this.$message.error("此文字已创建过");
            }
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    addversionHandle() {
      let obj = {
          version:'',
          grade:'',
          class:'',
        };
      this.versionList.push(obj);
    },
    delVersionHandle(index) {
    this.versionList.splice(index,1);
    },
    // 选择年级监听事件，需要选择课程
    gradeChange(val,index) {
      if(!this.isUpdate || this.hasUpdate) {
         this.versionList[index].class = '';
      }else {
        this.hasUpdate = true;
      }
      this.grades.forEach(item=>{
        if(item._id === val) {
           this.classes = new Array(item.class);
        }
      })
    },
    // 清空视频
    clearVideoHandle() {
      this.form.video = '';
      setTimeout(() => {
         let videoNode = document.querySelector('#videoNode');
        console.log(videoNode)
      }, 0);

    },
    dialogConfim() {
      this.$router.push("/admin/addArticle");
      Object.assign(this.$data, this.$options.data());
    },
    dialogCancel() {
      this.$router.push("/admin/articles");
      Object.assign(this.$data, this.$options.data());
    },
    onSubmit() {
      let _this = this,
        dispatch = "ADD_ADMIN_ITEM",
        url = "article";
      if (!this.form.charName || !this.form.phoneticize) {
        this.$message.error("内容未填写");
        return;
      }
      let versionInvalid = !!this.versionList.length;
      for (let i = 0; i < this.versionList.length; i++) {
        const item =  this.versionList[i];
        if(!item.version || !item.grade) {
          versionInvalid = false;
          break;
        }
      }
      if(this.versionList.length===1 && !this.versionList[0].version && !this.versionList[0].grade) versionInvalid = true;
      if (!versionInvalid) {
        this.$message.error("版本或年级未填写完整");
        return;
      }
      if (!this.form.video) {
        this.$message.error("未上传视频");
        return;
      }
      this.form.belongVersionList = this.versionList;
      // if (this.isMarkdownEditor) {
      //   this.form.markdown = this.$store.state.editor.value();
      // } else {
      //   this.form.html = this.$store.state.editor.$txt.html();
      // }

      if (this.isUpdate) {
        (dispatch = "UPDATE_ADMIN_ITEM"), (url = `article/${_this.form._id}`);
      }
      this.$store.dispatch(dispatch, {
        url: url,
        msg: _this.$message,
        data: _this.form,
        cb: () => {
          _this.$set(_this, "dialogVisible", true);
        }
      });
    },
    // 上传图片
    picChange(e) {
      let _this = this;
      let file = null;
      if(e && e.target.files) {
          file = e.target.files[0];
      }
      if(file) {
        var storeAs = file.name;
        client_pic.multipartUpload(storeAs, file).then(function (result) {
            console.log(result);
            _this.form.headerImg = result.url;
      }
        )}
    },
        // 上传视频
    videoChange(e) {
      let _this = this;
      let file = null;
      if(e && e.target.files) {
          file = e.target.files[0];
      }
      if(file) {
        var storeAs = file.name;
        let loading = this.$loading();
        console.log(client_video)
        client_video.listUploads().then(res=>{
          console.log(res)
        })
        var progress = function (p) {
              return function (done) {
                console.log(p);
                done();
              };
            };
        client_video.multipartUpload(storeAs, file,{
          progress:progress
        }).then(function (result) {
          loading.close();
            _this.form.video = 'http://video.duoxx.cn/'+result.name;
          _this.$nextTick(function(){
          var video;
          var scale = 0.8;
          var initialize = function() {
          // output = document.getElementById("output");
          var canvas=document.getElementById("myCanvas");
          document.querySelector(".capture-image")
          var captureImage = function() {
            console.log('captureImage')
            video = document.querySelector("#editor-header1 video");
            // canvas.width = video.offsetWidth * scale;
            // canvas.height = video.offsetHeight * scale;
            canvas.getContext('2d').drawImage(video, 0, 0);

            // var img = document.createElement("img");
            _this.form.headerImg = canvas.toDataURL("image/png");
            console.log(_this.form.headerImg);
            };
          // video.addEventListener('load',captureImage);
          captureImage();
          };
            // initialize();
          })
        })
    }
    },
  },
  mounted() {
    const _this = this;
    tools.qiniu(
      _this,
      "editor-header",
      "editor-header",
      "article/header",
      sourceLink => {
        _this.$set(_this.form, "headerImg", sourceLink);
      }
    );
      // 获取版本
      api._get({url:'query/version',data: {start: 0}}).then(res=>{
            this.versions = res.data.data.list;
      }).catch(error => {
        console.log(error);
      });
      // 获取年级
      api._get({url:'query/grade',data: {start: 0}}).then(res=>{
            this.grades = res.data.data.list;
      }).catch(error => {
        console.log(error);
      });
       // 获取标签
      api._get({url:'query/tag',data: {start: 0}}).then(res=>{
            this.tags = res.data.data.list;
      }).catch(error => {
        console.log(error);
      });
    if (!this.isUpdate) {
      return;
    }
    document.title = document.title.replace("添加", "编辑");
    api
      ._get({ url: `article/${this.$route.query.id}` })
      .then(res => {
        const article = res.data.data;
        _this.form = article;
        article.belongVersionList.forEach((item,index) => {
          _this.$set(_this.versionList,index,{version:'',grade:'', class:''});
          _this.versionList[index] = Object.assign(_this.versionList[index],item);
        });
        // if (article.html) {
        //   _this.$store.state.editor.$txt.html(article.html);
        // } else {
        //   this.$store.commit("SET_ITEM", {
        //     key: "isMarkdownEditor",
        //     val: true
        //   });
        // }
      })
      .catch(error => {
        console.log(error);
      });

  }
};
</script>

<style lang="stylus" scoped>
.el-form {
}
#add-article {
  display: flex;
  justify-content: center;

  .el-input, #editor-header, #editor,#editor-header1 {
    margin: 10px 0;
  }
.clearfix {
  clear:both;
}
  .moxie-shim.moxie-shim-html5 {
    width: 100%;
  }
  #editor-header {
    float:right;
  }
  #editor-header1 {
    float:left;
  }
  #editor-header,#editor-header1 {
    height: 200px;
    width:40%;
    display:inline-block;
    line-height: 200px;
    cursor: pointer;
    font-size: 2rem;
    overflow: hidden;
    text-align: center;
    img {
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
    }
  }

  .el-switch {
    margin-right: 20px;
  }
}
</style>
